package jannex.internal;

import jannex.JannexException;

public final class CloseUtils {

    private CloseUtils() {
    }

    public static void closeAll(AutoCloseable... closeables) {
        RuntimeException exception = null;
        for (AutoCloseable closeable : closeables) {
            try {
                if (closeable == null) {
                    continue;
                }
                closeable.close();
            } catch (Exception e) {
                if (exception == null) {
                    if (e instanceof RuntimeException) {
                        exception = (RuntimeException) e;
                    } else {
                        exception = new JannexException("Failed to close " + closeable.getClass().getSimpleName(), e);
                    }
                } else {
                    exception.addSuppressed(e);
                }
            }
        }
        if (exception != null) {
            throw exception;
        }
    }

    public static void close(AutoCloseable closeable) {
        if (closeable == null) {
            return;
        }
        try {
            closeable.close();
        } catch (JannexException e) {
            throw e;
        } catch (Exception e) {
            throw new JannexException("Failed to close " + closeable.getClass().getSimpleName(), e);
        }
    }

    public static RuntimeException close(AutoCloseable closeable, RuntimeException suppressing) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Throwable t) {
                suppressing.addSuppressed(t);
            }
        }
        return suppressing;
    }
}